package net.itxxw.order.service;


import net.itxxw.framework.domain.task.XcTask;
import net.itxxw.framework.domain.task.XcTaskHis;
import net.itxxw.order.dao.XcTaskHisRepository;
import net.itxxw.order.dao.XcTaskRepository;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author：ycpan
 * @date：Created in 2021/6/11 20:07
 * @description：
 * @modified By：
 * @version: $
 */
@Service
public class TaskService {
    @Autowired
    XcTaskRepository xcTaskRepository;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    XcTaskHisRepository xcTaskHisRepository;

    /**
     * 查询任务列表的实现
     * @param n 查询数量
     * @param updateTime 上次更新时间
     * @return
     */
    public List<XcTask> findTaskList(Date updateTime, int n) {
        //设置分页参数，取出前n 条记录
        //Pageable pageable = PageRequest.of(0,n);
        Pageable pageable=new PageRequest(0,n);
        Page<XcTask> xcTasks = xcTaskRepository.findByUpdateTimeBefore(pageable,updateTime);
        List<XcTask> xcTasksList = xcTasks.getContent();
        return xcTasksList;
    }

    /**
     * //发送消息
     * @param xcTask 任务对象
     * @param ex 交换机id
     * @param routingKey
     */
    @Transactional
    public void publish(XcTask xcTask,String ex,String routingKey){
     //查询任务
        Optional<XcTask> taskOptional = xcTaskRepository.findById(xcTask.getId());
        if(taskOptional.isPresent()){
            XcTask xcTaskopt=taskOptional.get();
            //String exchange, String routingKey, Object object
            rabbitTemplate.convertAndSend(ex,routingKey,xcTaskopt);
         //更新任务时间为当前时间
            xcTask.setUpdateTime(new Date());
            xcTaskRepository.save(xcTaskopt);
        }
    }

    @Transactional
    public int getTask(String taskId,int version){
        int i = xcTaskRepository.updateTaskVersion(taskId,version);
        return i;
    }

    //删除任务
    @Transactional
    public void finishTask(String taskId){
        Optional<XcTask> taskOptional = xcTaskRepository.findById(taskId);
        if(taskOptional.isPresent()){
            XcTask xcTask = taskOptional.get();
            xcTask.setDeleteTime(new Date());
            XcTaskHis xcTaskHis = new XcTaskHis();
            BeanUtils.copyProperties(xcTask, xcTaskHis);
            xcTaskHisRepository.save(xcTaskHis);
            xcTaskRepository.delete(xcTask);
        }
    }


}
